/**
 * Created by bethinner on 6/7/16.
 */
import React, { Component } from 'react';

import { connect } from 'react-redux'
import browserHistory from 'react-router/lib/browserHistory'
import NavigationBar from '../components/NavigationBar'
import GreenButton from '../components/GreenButton'
import EditText from '../components/EditText'
import Checkbox from '../components/CheckBox'

import {fetchPost} from '../utils/httpRequest'
import MessageAlert from '../components/MessageAlert'
import cookie from 'react-cookie'

export default class VerifyPhoneContainer extends Component {
    constructor(props) {
        super(props);
        this._reduceCount = this.reduceCount.bind(this);
        this._startCount = this.startCount.bind(this);
        this._handle = this.handle.bind(this);
        this._btnClick = this.btnClick.bind(this);
        this._phoneNumberChange = this.phoneNumberChange.bind(this);
        this.state = {
            securityCode: "",
            phoneNumber: "",
            password: "",
            checked: true,
            returnObj: {},
            showMessage: false,
            countSecond: 60,
            disabledButton: false
        }
        this.autoLogin=this.autoLogin.bind(this);

    }

    componentWillMount() {
    }

    componentDidMount() {
        if (this.state.disabledButton) {
            this.interval = setInterval(this._reduceCount, 1000);
        }
    }

    phoneNumberChange(event) {
        this.state.phoneNumber = event.target.value;
    }



    btnClick() {
        // 调用发送验证码接口,发送成功跳转到验证验证码界面
        let param = {mobile: this.state.phoneNumber, msg_type: this.props.location.state.type};
        $('#loadingToast').show();
        if(this.state.phoneNumber.trim().length!=11){
            alert('请输入11位手机号');
            $('#loadingToast').hide();
            return ;
        }

        fetchPost('sendCap_Code', param).then(
            response => response.json()
        ).then(
            json => {
                $('#loadingToast').hide();
                this.state.returnObj = json;
                if (this.state.returnObj.code == 0) {
                    //获取验证码成功
                    this._startCount();
                } else {
                    this.setState({showMessage: true});
                }
                this.setState({returnObj: json});
            }
        )
    }

    startCount() {
        this.setState({countSecond: 60, disabledButton: true})
        this.interval = setInterval(this._reduceCount, 1000);
    }

    reduceCount() {
        if (this.state.countSecond > 0) {
            this.setState({
                countSecond: this.state.countSecond - 1,
                disabledButton: true
            });
        } else {
            clearInterval(this.interval);
            this.setState({
                disabledButton: false
            });

        }

    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }

    securityCodeChange(event) {
        this.state.securityCode = event.target.value;
    }

    chBtnStyle(checked){
        if(checked){
            $(".weui_btn").removeClass("weui_btn_disabled");
            $(".weui_btn").removeClass("weui_btn_default");
            $(".weui_btn").addClass("weui_btn_primary");
        }else{
            $(".weui_btn").removeClass("weui_btn_primary");
            $(".weui_btn").addClass("weui_btn_disabled");
            $(".weui_btn").addClass("weui_btn_default");
        }
    }

    checkBoxChange(e) {
        this.chBtnStyle(e.target.checked);
        this.setState({
            checked: e.target.checked
        });
    }

    verifyPhone() {
        if(!this.state.checked){
            return;
        }
        if(!this.state.phoneNumber.trim()||(this.state.phoneNumber.trim()&&this.state.phoneNumber.trim().length!=11)){
            alert('请输入正确手机号');
            return;
        }
        if(!this.state.securityCode.trim()){
            alert('请输入验证码');
            return;
        }

        // 调用接口判断验证匹配正确
        if (this.state.checked) {
            var b = /^[\w]{6,20}$/;
            if (b.test(this.state.password) && !(/^\d+$/.test(this.state.password)) && !(/^[A-Za-z]+$/.test(this.state.password))) {
                $('#loadingToast').show();
                let param = {mobile: this.state.phoneNumber,
                    msg_type: this.props.location.state.type,
                    code: this.state.securityCode,
                    password: this.state.password};
                fetchPost('verifyCode', param).then(
                    response => response.json()
                ).then(
                    json => {

                        $('#loadingToast').hide();
                        this.state.returnObj = json;
                        if (this.state.returnObj.code == 0) {
                            //对应处理成功
                            this.autoLogin(this.state.returnObj.data.ts,this.state.returnObj.data.loginSign);
                        } else {
                            this.setState({returnObj: json,showMessage: true});
                        }
                    }
                )
            }else {
                alert("密码格式错误,6-20位字母加数字组合");
            }
        } else {
            alert("接收注册协议才能注册");
        }

    }

    getVerifyCodeButton() {
        if (this.state.disabledButton) {
            return (<span style={buttonStyle} disabled>
                |重新获取({this.state.countSecond})s</span>)
        } else {
            return (<span style={buttonStyle} onClick={this._btnClick}>
                |获取验证码</span>)
        }

    }
    passwordChange(event) {
        this.state.password = event.target.value;
    }

    autoLogin(ts,loginSign) {
        $('#loadingToast').show();
        let param = {user_id: this.state.phoneNumber, password: this.state.password};
        if(ts){
            param.ts=ts;
            param.loginSign=loginSign;
        }
        //console.log(param);
        fetchPost('login', param).then(
            response => response.json()
        ).then(
            json => {
                $('#loadingToast').hide();
                this.state.returnLoginObj = json;
                //console.log(json);
                if (this.state.returnLoginObj.code == 0) {

                    //登录成功
                    cookie.save('mobile', param.user_id, {path: '/', maxAge: 3 * 24 * 3600});
                    cookie.save('smid', json.data.smid, {path: '/', maxAge: 3 * 24 * 3600});
                    cookie.save('o2osign',json.data.o2osign,{path:'/',maxAge:3*24*3600});

                    if (this.props.location.state.wePiao){
                        let param2 = {mobile: param.user_id,o2osign:json.data.o2osign};
                        fetchPost('getWePiaoUrl', param2).then(
                                response => {
                                $('#loadingToast').hide();
                                return  response.json()
                            }
                        ).then(
                                json2 => {
                                if (json2.code == 0) {
                                    //获取微票跳转链接成功
                                    location.href=json2.data;
                                } else {
                                    location.href="http://m.wepiao.com";
                                }
                            }
                        )
                        return ;
                    }else{
                        browserHistory.replace({
                            pathname: `/index`,
                        });
                    }
                }else{
                    this.setState({returnObj: json,showMessage:true});
                }

            }
        )
    }

    handle(type) {
        var that = this;
        return function () {
            that.setState({showMessage: false});
        }
    }

    getMessageAlert() {
        if (this.state.showMessage == true) {
            return (<MessageAlert message={this.state.returnObj.msg}
                                  type={1}
                                  handle={this._handle}/>)
        } else {
            return ""
        }
    }

    getCheckBox(){
        if (this.props.location.state.type==0){
            return(<div style={{width:"76%",margin: "6px auto 5px auto",textAlign: 'left'}}>
                <Checkbox checked={this.state.checked} onChange={this.checkBoxChange.bind(this)}
                          style={{marginRight:"6px"}}/>
                <span style={spanNormalStyle}>同意《</span>
                <span style={spanBlueStyle}>注册协议</span>
                <span style={spanNormalStyle}>》</span>
            </div>) ;
        }else{
            return "";
        }

    }
    render() {
        return (
            <div style={{background:"white",height:"100%"}}>
                    <div style={{textAlign:"center"}}>
                        <NavigationBar Title={titles[this.props.location.state.type]} LeftBar="true"/>
                        {this.getMessageAlert()}
                        <div style={{width:"76%",margin: "36px auto 0 auto" ,textAlign:"left"}}>
                            <div className="antd-row">
                                <div style={{width:"66.66666667%",float:"left"}}>
                                    <input
                                        style={editStyle}
                                        placeholder="请输入手机号"
                                        type="tel"
                                        onChange={this._phoneNumberChange}/>
                                </div>
                                <div style={{width:"33.33333333%",float:"left"}}>
                                    {this.getVerifyCodeButton()}
                                </div>
                                <div style={{clear:"both"}}></div>
                            </div>
                        </div>

                        <div
                            style={{backgroundColor:"#6BAC72",height:"1px" ,width:"76%",margin: "0 auto 15px auto"}}></div>


                        <div style={{width:"76%",margin: "0 auto 0 auto" ,textAlign:"left"}}>
                                    <input
                                        style={editStyle}
                                        placeholder="请输入验证码"
                                        onChange={this.securityCodeChange.bind(this)}/>
                        </div>
                        <div style={{backgroundColor:"#6BAC72",height:"1px" ,width:"76%",margin: "0 auto"}}></div>



                            <div style={{width:"88%",margin: "15px 0 0 12%" ,textAlign:"left"}}>
                                <input
                                    style={{
                                    width:"88%",
                                    outline: "none",
                                    border:"none",
                                    fontSize:"14px",
                                    height:"28px"}}
                                    placeholder="请设置6~20位数字和字母组合密码"
                                    type="password"
                                    onChange={this.passwordChange.bind(this)}/>
                            </div>
                        <div
                            style={{backgroundColor:"#6BAC72",height:"1px" ,width:"76%",margin: "0 auto"}}></div>
                        {this.getCheckBox()}
                        {<div style={{marginTop:"16px"}}></div>}
                        <GreenButton onClick={this.verifyPhone.bind(this)} text="确定"/>
                        {/*<div style={{width:"76%",margin: "-6% auto 0 auto",textAlign: 'left'}}>
                            <span style={spanBlueStyle}>提示:设置登录密码后，可通过手机号和登录密码登录 </span>
                        </div>*/}
                        <img style={{width:"80%" ,margin: "15% auto 0"}} src="/public/img/img_line.png"/>
                        <div style={{color:'#76EE00' ,marginTop: '10px',fontSize:"12px"}}>
                            在市民卡App或网站注册过的用户可直接使用手机号登录
                        </div>
                    </div>
            </div>

        )
    }
}

let titles = ["设置密码", "重置密码"];

let spanNormalStyle={
    margin:"0",
    fontSize:"10px",
    color:"#9B9B9B"};

let spanBlueStyle={
    fontSize:"10px",
    color:"#00BFFF"};
let editStyle={
    outline: "none",
    border:"none",
    fontSize:"14px",
    height:"28px"};
let buttonStyle = {
    backgroundColor: "white",
    borderColor: "white",
    color: "green",
}
VerifyPhoneContainer.defaultProps = {}

VerifyPhoneContainer.propTypes = {}
module.exports = VerifyPhoneContainer;


